<?php
/**
 * 价格趋势API逻辑
 * @author 王勇程 <laughskydragon@qq.com>
 */

namespace app\api\logic;

use app\common\logic\Price as CommonPrice;

class Price extends ApiBase
{
    /**
     * 公共价格逻辑实例
     */
    protected static $commonPriceLogic;
    
    /**
     * 构造方法
     */
    public function __construct()
    {
        // 执行父类构造方法
        parent::__construct();
        
        empty(static::$commonPriceLogic) && static::$commonPriceLogic = new CommonPrice();
    }
    
    /**
     * 获取价格趋势
     */
    public function getPriceTrend($data = [])
    {
        // 1. JWT解析获取user_id（如果需要）
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            if ($userData) {
                $data['user_id'] = $userData['user_id'];
            }
        }

        // 2. 过滤参数并传递给 common 层逻辑
        $queryData = [];
        $allowedFields = ['product_id', 'period', 'start_date', 'end_date', 'user_id'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }

        // 3. 调用 common 层获取趋势数据
        $result = static::$commonPriceLogic->getPriceTrend($queryData);

        // 4. 适配 API 返回格式
        if (is_array($result) && isset($result[0]) && $result[0] === RESULT_SUCCESS) {
            return [API_CODE_NAME => 0, API_MSG_NAME => '获取成功', 'data' => $result[2]];
        }
        
        $msg = is_array($result) && isset($result[1]) ? $result[1] : '获取失败';
        return [API_CODE_NAME => 1001001, API_MSG_NAME => $msg];
    }
    
    /**
     * 获取价格历史
     */
    public function getPriceHistory($data = [])
    {
        // 1. JWT解析获取user_id（如果需要）
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            if ($userData) {
                $data['user_id'] = $userData['user_id'];
            }
        }
        
        // 2. 过滤掉API相关字段，只保留数据库查询相关字段
        $queryData = [];
        $allowedFields = ['product_id', 'start_date', 'end_date', 'user_id'];
        foreach ($allowedFields as $field) {
            if (isset($data[$field])) {
                $queryData[$field] = $data[$field];
            }
        }
        
        // 3. 调用common层业务逻辑
        $result = static::$commonPriceLogic->getPriceHistory($queryData);
        
        return $result;
    }
    
    /**
     * 获取市场统计
     */
    public function getMarketStats($data = [])
    {
        // 1. JWT解析获取user_id（如果需要）
        $token = $data['user_token'] ?? '';
        if (!empty($token)) {
            $userData = get_user_by_token($token);
            if ($userData) {
                $data['user_id'] = $userData['user_id'];
            }
        }
        
        // 2. 检查是否为市场统计请求
        $isMarketStatsRequest = isset($data['market_stats_mode']) && $data['market_stats_mode'] == 1;
        
        if ($isMarketStatsRequest) {
            // 市场统计模式：过滤掉API相关字段，只保留数据库查询相关字段
            $queryData = [];
            $allowedFields = ['category_id', 'user_id'];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $queryData[$field] = $data[$field];
                }
            }
            
            // 调用Market的getMarketStats逻辑
            $marketWhere = $queryData;
            $marketWhere['status'] = 1;
            
            // 获取统计数据
            $totalProducts = $this->modelProduct->stat($marketWhere, 'count');
            $totalValue = $this->modelProduct->stat($marketWhere, 'sum', 'market_price');
            $avgPrice = $totalProducts > 0 ? round($totalValue / $totalProducts, 2) : 0;
            
            $result = [
                'total_products' => $totalProducts,
                'total_value' => $totalValue,
                'avg_price' => $avgPrice,
                'update_time' => date('Y-m-d H:i:s')
            ];
        } else {
            // 原有市场统计模式
            // 过滤掉API相关字段，只保留数据库查询相关字段
            $queryData = [];
            $allowedFields = ['category_id', 'user_id'];
            foreach ($allowedFields as $field) {
                if (isset($data[$field])) {
                    $queryData[$field] = $data[$field];
                }
            }
            
            // 调用common层业务逻辑（如果存在）
            // 这里需要根据实际的common层Price逻辑来调用
            $result = static::$commonPriceLogic->getMarketStats($queryData);
        }
        
        return $result;
    }
}